package com.summer.common.lib.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

/**
 * 项目配置文件读取工具
 */
public class WebConfig {

    public static final String CONTEXT_NAME = WebConfig.class.getName();

    private static ServletContext servletContext;

    private static ConfigLoader configLoader;

    public WebConfig(ServletContext servletContext) {
        servletContext = servletContext;
        configLoader = new ConfigLoader();
        servletContext.setAttribute(CONTEXT_NAME, this);
    }

    public static ServletContext getServletContext() {
        return servletContext;
    }

    /**
     * 根据key获取对应的值
     *
     * @param key
     * @param <C>
     * @return
     */
    private static <C> C getValue(String key) {
        return (C) configLoader.getApplicationConfigMap().get(key);
    }

    /**
     * 根据配置文件名称获取配置
     *
     * @param key 配置key
     * @param t   配置文件对应实体类型
     * @param <T>
     * @return
     */
    private static <T> T getValue(String key, Class<T> t) {
        Map<String, Object> configMap = configLoader.getConfigLoaderTemplateMap().get(key);
        if (configMap == null) {
            return null;
        }
        return JSONObject.parseObject(JSON.toJSONString(configMap), t);
    }


    public static <C> C keyParser(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        String separator = ".";
        String[] separatorKeys = null;
        if (key.contains(separator)) {
            separatorKeys = key.split("\\.");
        } else {
            return getValue(key);
        }
        Map<String, Map<String, Object>> finalValue = new HashMap<>();
        for (int i = 0; i < separatorKeys.length - 1; i++) {
            if (i == 0) {
                finalValue = (Map) configLoader.getApplicationConfigMap().get(separatorKeys[i]);
                continue;
            }
            if (finalValue == null) {
                break;
            }
            finalValue = (Map) finalValue.get(separatorKeys[i]);
        }
        return finalValue == null ? null : (C) finalValue.get(separatorKeys[separatorKeys.length - 1]);
    }

    public static <T> T keyParser(String key, Class<T> t) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return getValue(key, t);
    }

}